﻿#region [===== Using =====]
using System;
using System.Web.UI;
using Microsoft.SharePoint;
#endregion

namespace TPG.SharePoint.Workflow
{
    /// <summary>
    /// A base control for controls using the hosted control framework.
    /// </summary>
    public abstract class  WorkflowControl
        : UserControl
    {
        #region [===== Fields =====]
        IWorkflowPage _page;
        #endregion

        #region [===== Properties =====]
        /// <summary>
        /// Gets a value indicating whether the form is being loaded and 
        /// accessed for the first time.
        /// </summary>
        /// <remarks>
        /// This value is similar to the 
        /// <see cref="System.Web.UI.Page.IsPostBack" /> property. However,
        /// some workflow forms are loaded as the result of a client postback 
        /// request. For these forms the IsPostBack property does not return 
        /// a value that can be used to initialize the form once, since it will
        /// always return true.
        /// </remarks>
        protected bool IsInitialLoad
        {
            get { return _page.IsInitialLoad; }
        }

        /// <summary>
        /// Gets the name of the workflow.
        /// </summary>
        protected string WorkflowName
        {
            get { return _page.WorkflowMetaData.WorkflowName; }
        }

        /// <summary>
        /// Getst the <see cref="PageType" /> of the workflow page
        /// that this control is placed on.
        /// </summary>
        protected PageType PageType
        {
            get { return _page.WorkflowMetaData.PageType; }
        }

        internal IWorkflowPage WorkflowPage
        {
            get { return _page; }
        }
        #endregion

        #region [===== Protected methods =====]
        /// <summary>
        /// Checks if the control is hosted in the hosted control framework
        /// correctly.
        /// </summary>
        /// <param name="e">An <see cref="EventArgs"/> containing event data.
        /// </param>
        protected override void OnInit(EventArgs e)
        {
            _page = this.Page as IWorkflowPage;
            if (_page == null)
                throw new WorkflowException(
                    "Must be added to a page implementing IWorkflowPage.");

            base.OnInit(e);
        }
        #endregion

        #region [===== Internal static methods =====]
        internal static WorkflowControl CreateFormControl(Page page, string formUrl)
        {
            WorkflowControl control = page.LoadControl(formUrl) as WorkflowControl;
            if (control == null)
                throw new WorkflowException(
                    "Control does not derive from WorkflowControl.");

            return control;
        }
        #endregion
    }
}
